from socket import *
import json
import struct
from optparse import OptionParser

def recv_file(head_dir, tcp_client):
    filename = head_dir['filename']
    filesize = head_dir['filesize_bytes']
    print("[+]filename: " + filename[0])
    print("[+]filesize: " + str(filesize))
    recv_len = 0
    f = open(filename[0], 'wb')
    while recv_len < filesize:
        if (filesize > 1024):
            recv_mesg = tcp_client.recv(1024)
            recv_len += len(recv_mesg)
            f.write(recv_mesg)
        else:
            recv_mesg = tcp_client.recv(filesize)
            recv_len += len(recv_mesg)
            f.write(recv_mesg)
    f.close()
    print('[+]File transfer successful')

def main():
    parser = OptionParser("Usage:%prog -u <address> -p <port>")
    parser.add_option('-u', type='string', dest='ip', help='input ip')
    parser.add_option('-p', type='string', dest='port', help='input port')
    options, args = parser.parse_args()
    t_port = int(options.port)
    t_ip = options.ip
    print(t_ip, t_port)

    # socket init
    tcp_clint = socket(AF_INET, SOCK_STREAM)
    ip_port = (t_ip, t_port)
    tcp_clint.connect_ex(ip_port)
    print('[+]Waiting for server response...')

    struct_len = tcp_clint.recv(4)
    struct_info_len = struct.unpack('i', struct_len)[0]
    print('[+]Receive message length:' + str(struct_info_len))
    head_info = tcp_clint.recv(struct_info_len)
    head_dir = json.loads(head_info.decode('utf-8'))
    print('[+]print body info:' + str(head_dir))


if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print('error')
